#!/bin/bash

if [ "$TERM" == "screen" ]; then
 echo "Running as a background job in screen, won't use any sudo commands"
 echo "exiting..."
 exit 0
fi

if [ ! -f "$1" ]; then
	echo call with $0 smcardimage
	exit 1
fi

KPARTX=`which kpartx`
if [ "$KPARTX" == "" ]; then
	echo "kpartx not available, not checking SD card image"
	exit
fi

# find unused loop device
free_loop_device() {
	for i in 0 1 2 3 4 5 6 7 8 9; do
		for j in 0 1 2 3 4 5 6 7 8 9 0; do
			loid=$i$j
			loid=`echo $loid | sed 's/^0*//'`
			if [ "$loid" == "" ]; then
				continue
			fi
			if [ ! -e /dev/loop$loid ]; then
				LOOPDEVICE=loop$loid
				return
			fi
		done
	done
}

free_loop_device
if [ "$LOOPDEVICE" == "" ]; then
	echo "couldn't find usuable loopback device name, existing..."
	exit 1
else
	echo "using $LOOPDEVICE"
fi
	
sudo losetup /dev/${LOOPDEVICE} $1
sudo kpartx -a  /dev/${LOOPDEVICE}
ls -l /dev/mapper
sudo dosfsck -a /dev/mapper/${LOOPDEVICE}p1
sudo fsck.ext4 -v -f  /dev/mapper/${LOOPDEVICE}p2
sudo fsck.f2fs -y -f  /dev/mapper/${LOOPDEVICE}p2
sudo kpartx -d /dev/${LOOPDEVICE}
sudo losetup -d /dev/${LOOPDEVICE}


